package com.sinoglobal.ningxia.http;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.orhanobut.logger.Logger;
import com.sinoglobal.ningxia.exception.NoDataException;
import com.sinoglobal.ningxia.utils.FileLocalCache;
import com.sinoglobal.ningxia.utils.ItktLog;
import com.sinoglobal.ningxia.utils.LocalCache;
import com.sinoglobal.ningxia.utils.TextUtil;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author qiwx
 * @title: ConnectionUtil.java
 * @package com.sinoglobal.ningxia.http
 * @description: myTask(用一句话描述该文件做什么)
 * @date 2015-3-6 下午4:28:00
 */
public class ConnectionUtil {
    private static final String ACCEPT = "Accept-Charset";
    private static final String UTF8 = "UTF-8";
    private static final String UTF8_ES = "UTF-8,*";
    private static final String CONNECTION_JSON = "json";
    private static final String APP_JSON = "APPLICATION/JSON";
    private static final String REQUEST_URL = "请求：URL:-->:";
    private static final String RESPONSE_STATUS = "响应状态码：";
    public static final String REQUEST_ERROR = "请求数据失败";

    // 正式环境
    public static String localUrl = "http://nxtv.sinosns.cn";

    // 内部线上环境
//	 public static String localUrl = "http://php.test.sinosns.cn";
    // 测试环境
//	public static String localUrl = "http://192.168.10.11:8007";
    public static final String URL = localUrl + "/app/?";
    // 宁夏会议平台地址
    public static final String PORTAL_ENTRY = "http://common.nxtv.com.cn/meeting/?phone=";
    // 宁夏台通讯录地址
    public static final String PORTAL_CONTACTS = "http://common.nxtv.com.cn/contact?phone=";
    // 宁夏台记着开启直播之前的配置地址地址
    public static final String NINGXIA_LIVE_CONFIG = "http://wap.nxtv.cn/reporterlive/?phone=";
    // 宁夏 会议平台,太通讯录里,直播判读接口
//  public static final String PORTAL_VAILED = "http://common.nxtv.com.cn/contact/api/?phone=";//旧接口 被替换 2017年5月9日09:11:52
    public static final String PORTAL_VAILED = "http://common.nxtv.com.cn/libs/?mod=getapplimit&phone=";//新接口
    // 微门户地址
    public static final String MicDoorAdress = localUrl;
    //捞饺子模块 登录正式url
    public static final String DUMPLING_LOGIN_URL = "http://nxtv.sinosns.cn/app";
    //捞饺子模块 登录测试url
//	public static final String DUMPLING_LOGIN_URL = "http://192.168.10.11:8007/app";  


    private static Date serverDate; // 服务器时间

    public static Date getServerDate() {
        return serverDate;
    }

    public static String getUrl(String request) {
        String result = null;
        if (request == null || request.trim().equals(""))
            result = URL;
        else
            result = URL + request;
        result.trim();
        return result;

    }

    private static String getCacheFileName(Map<String, Object> params) {
        StringBuffer sb;
        sb = new StringBuffer();
        if (params != null) {

            for (String key : params.keySet()) {
                sb.append(params.get(key));
            }
        }
        return sb.toString();

    }

    /**
     * @param url
     * @param type get或post 参数当传递post时 设置params，get时params设置为null
     * @return
     * @throws Exception
     * @author sbk
     * @createdate 2014-5-8 下午8:34:42
     * @Description: 访问网络
     */
    public static String send(boolean saveCache, String url, String type, Map<String, Object> params) throws Exception {
        String fileName = null;
        String resquestUrl;
        resquestUrl = getUrl(url);
        ItktLog.e(REQUEST_URL + "---" + type + "---" + saveCache + "---" + resquestUrl);
        if (saveCache) {
            fileName = LocalCache.getFileName(resquestUrl, params);// 保证读写文件名相同
            // if (params == null)
            // fileName = LocalCache.getFileName(resquestUrl);
            // else
            // fileName = LocalCache.getFileName(resquestUrl +
            // getCacheFileName(params));
        }
        String json = JSON.toJSONString(params);
        System.out.println("请求信息：" + json);
        // 如不转码，服务器可能会接收不全
        // return httpRequest(resquestUrl, type,List<NameValuePair>
        // params,fileName);
        return httpRequest(resquestUrl, type, params, fileName);
    }

    /**
     * @param url
     * @param type get或post 参数当传递post时 设置params，get时params设置为null
     * @return
     * @throws Exception
     * @author sbk
     * @createdate 2014-5-8 下午8:34:42
     * @Description: 访问网络
     */
    public static String send(String url, String type, Map<String, Object> params) throws Exception {
        String fileName = null;
        ItktLog.e(REQUEST_URL + "---" + type + "---" + url);
        String json = JSON.toJSONString(params);
        System.out.println("请求信息：" + json);
        return httpRequest(url, type, params, fileName);
    }

    private static String httpRequest(String requestUrl, String type, Map<String, Object> params, String fileName) throws Exception {
        String result = null;

        HttpResponse httpResponse;

        if ("get".equalsIgnoreCase(type)) {
            HttpGet httpGet = new HttpGet(requestUrl);
            // 取得HTTP response
            httpResponse = new DefaultHttpClient().execute(httpGet);
            // httpResponse = CustomerHttpClient.getInstance().execute(httpGet);

            if (httpResponse.getStatusLine().getStatusCode() == 200)
                result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
            ItktLog.e("get 返回数据：" + result);
        } else {
            HttpPost httpRequest = new HttpPost(requestUrl);

            try {
                // 发出HTTP request
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                if (params != null) {
                    for (String key : params.keySet()) {
                        ItktLog.e("key:" + key + ", value:" + params.get(key));
                        nvps.add(new BasicNameValuePair(key, params.get(key) == null ? null : params.get(key).toString()));
                    }
                    params.clear();
                    params = null;
                }
                httpRequest.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
                // 取得HTTP response
                result = execute(httpRequest, null);
            } catch (Exception e) {
                e.printStackTrace();
                result = "";
            }
        }

        if (TextUtil.stringIsNull(result)) {
            throw new NoDataException("request not data :" + requestUrl);
        }
        if (null != fileName) {
            LocalCache.writeFileCache(fileName, result);
        }
        // LogUtil.e("请求数据：" + result);
        return result;

    }

	/*
     * private static String httpRequest(String u, String type, String fileName)
	 * throws Exception { URL url = new URL(u); // 第二步：获取HttpURLConnection对象
	 * HttpURLConnection huc = (HttpURLConnection) url.openConnection(); //
	 * huc.setRequestProperty("Accept", "application/json"); //
	 * huc.setRequestProperty("Content-Type", "application/json");
	 * huc.setRequestProperty("Content-type", "text/html");
	 * huc.setRequestProperty("Accept-Charset", "utf-8");
	 * huc.setRequestProperty("contentType", "utf-8"); // 第三步：设置请求超时时间
	 * huc.setConnectTimeout(15000); huc.setReadTimeout(15000);
	 * huc.setDoInput(true); // huc.setDoOutput(true); // 设置 请求方式Get Post if
	 * ("get".equalsIgnoreCase(type)) { huc.setRequestMethod("GET"); } else {
	 * huc.setRequestMethod("POST"); } //
	 * huc.getOutputStream().write(json.getBytes());
	 * 
	 * LogUtil.e("返回的响应码：" + huc.getResponseCode()); // 第四步：获取响应吗，进行判断 String
	 * result = ""; if (huc.getResponseCode() == 200) { // HTTP响应消息获取状态码
	 * BufferedReader in = new BufferedReader(new
	 * InputStreamReader(huc.getInputStream())); String line; while ((line =
	 * in.readLine()) != null) { result += line; } in.close();
	 * Log.e("result-->", result);
	 * 
	 * } if (TextUtil.stringIsNull(result)) { throw new
	 * NoDataException("request not data :" + url); } if (null != fileName) {
	 * LocalCache.writeFileCache(fileName, result); } //
	 * huc.getOutputStream().flush(); // huc.getOutputStream().close(); return
	 * result; }
	 */

    private static String execute(HttpUriRequest req, String fileName) throws Exception {
        long startTime = System.currentTimeMillis();

        String result = null;
        InputStream instream = null;
        try {
            HttpResponse response = executeLoad(req);
            if (response != null) {
                int statusCode = response.getStatusLine().getStatusCode();
                ItktLog.d(RESPONSE_STATUS + statusCode);
                switch (statusCode) {
                    case HttpStatus.SC_OK:
                        // result = parseResponse(response, instream);
                        result = EntityUtils.toString(response.getEntity(), UTF8);
                        Log.e("result-->", result);
                        break;
                    case HttpStatus.SC_FORBIDDEN: // 验证未通过
                        break;
                    case HttpStatus.SC_NOT_FOUND: // 请求错误
                        break;
                }
            }
        } finally {
            FileLocalCache.closeInputStream(instream);
        }

        // 打包时应该注释
        long endTime = System.currentTimeMillis();
        String info = "请求：Time:" + (endTime - startTime) + "-->:" + req.getURI();
        ItktLog.d(info);
        if (TextUtil.stringIsNull(result)) {
            throw new NoDataException("request not data :" + req.getURI());
        }
        if (null != fileName) {
            LocalCache.writeFileCache(fileName, result);
        }
        // FileLocalCache.saveFile(info, result);
        return result;
    }

    // 普通键值对，上传图片用
    public static String post(String path, Map<String, Object> params) throws Exception {
        ItktLog.e(REQUEST_URL + path);
        path = URL + path;
        Logger.e(REQUEST_URL + path);
        HttpPost httpost = new HttpPost(path);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if (params != null) {
            for (String key : params.keySet()) {
                ItktLog.e("key:" + key + ", value:" + params.get(key));
                nvps.add(new BasicNameValuePair(key, params.get(key) == null ? null : params.get(key).toString()));
            }
            params.clear();
            params = null;
        }
        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        return execute(httpost, null);
    }

    // 测试发表评论用
    public static String post(String url, String json) throws Exception {
        url = URL + url;
        HttpPost httpost = new HttpPost(url);
        ItktLog.d("json==>" + json);
        StringEntity se = new StringEntity(json, HTTP.UTF_8);
        httpost.setEntity(se);
        httpost.setHeader(CONNECTION_JSON, APP_JSON);
        httpost.setHeader(HTTP.CONTENT_TYPE, APP_JSON);
        Log.e("url==>", URL);
        Log.e("post-->", json);
        return execute(httpost, null);
    }

    /**
     * @param req
     * @return
     * @throws Exception
     * @author ty
     * @createdate 2012-11-3 下午9:46:54
     * @Description: 加载数据
     */
    public static HttpResponse executeLoad(HttpUriRequest req) throws Exception {
        // HttpClient httpclient = CustomerHttpClient.getInstance();
        // 修改单例，
        // HttpClient httpclient = new DefaultHttpClient();
        /*
         * if (NetWorkUtil.ONLYWAP == true) { HttpHost proxy = new
		 * HttpHost(DEPUTIZW_IP, 80);
		 * httpclient.getParams().setParameter(ConnRoutePNames
		 * .DEFAULT_PROXY,proxy); }
		 */
        req.addHeader(ACCEPT, UTF8_ES);
        HttpResponse response = new DefaultHttpClient().execute(req);
        return response;
    }

    /**
     * 取得响应的信息流
     *
     * @param response
     * @param instream
     * @return
     * @throws Exception
     */
    /*
     * private static String parseResponse(HttpResponse response,InputStream
	 * instream) throws Exception { String result = null; HttpEntity entity =
	 * response.getEntity(); if (entity != null) { instream =
	 * entity.getContent(); result = TextUtil.InputStreamToString(instream); }
	 * return result; }
	 */
}
